package com.cn.parks.servlet;

import com.alibaba.fastjson.JSON;
import com.cn.parks.dao.ParkingSeatDao;
import com.cn.parks.dao.TempParkingDao;
import com.cn.parks.dao.UserCarDao;
import com.cn.parks.dao.UserDao;
import com.cn.parks.dao.impl.ParkingSeatDaoImpl;
import com.cn.parks.dao.impl.TempParkingDaoImpl;
import com.cn.parks.dao.impl.UserCarDaoImpl;
import com.cn.parks.dao.impl.UserDaoImpl;
import com.cn.parks.entity.TempParking;
import com.cn.parks.entity.UserCar;
import com.cn.parks.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@WebServlet("/tempParking/*")
public class TempParkingServlet extends HttpServlet {
    private TempParkingDao tempParkingDao = new TempParkingDaoImpl();
    private UserCarDao userCarDao = new UserCarDaoImpl();
    private UserDao userDao = new UserDaoImpl();
    private ParkingSeatDao parkingSeatDao = new ParkingSeatDaoImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        
        String pathInfo = request.getPathInfo();
        try {
            if ("/list".equals(pathInfo)) {
                // 获取所有记录
                response.getWriter().write(JSON.toJSONString(Result.success(tempParkingDao.getAll())));
            } else if ("/search".equals(pathInfo)) {
                // 搜索车牌号
                String carNum = request.getParameter("key");
                response.getWriter().write(JSON.toJSONString(Result.success(tempParkingDao.getByCarNum(carNum))));
            } else if ("/current".equals(pathInfo)) {
                // 获取当前停车记录
                response.getWriter().write(JSON.toJSONString(Result.success(tempParkingDao.getNotOutCars())));
            } else if ("/stats".equals(pathInfo)) {
                // 获取统计数据
                Map<String, Object> stats = new HashMap<>();
                stats.put("current", tempParkingDao.getNotOutCars().size());
                stats.put("todayIn", tempParkingDao.getTodayIn());
                stats.put("todayOut", tempParkingDao.getTodayOut());
                stats.put("todayIncome", tempParkingDao.getTodayIncome());
                // TODO: 添加其他统计数据
                response.getWriter().write(JSON.toJSONString(Result.success(stats)));
            }
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error(e.getMessage())));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        
        String pathInfo = request.getPathInfo();
        try {
            if ("/entry".equals(pathInfo)) {
                // 车辆入场
                String requestBody = request.getReader().readLine();
                UserCar car = JSON.parseObject(requestBody, UserCar.class);
                car.setCarType(3);
                car.setStatus(0);
                TempParking parking = new TempParking();
//                parking.setTempId(UUID.randomUUID().toString().replace("-", ""));
                parking.setCarNum(car.getCarNumber());
                parking.setUserId(car.getUserId());
                // 检查用户是否存在
                if (userDao.getById(parking.getUserId()) == null) {
                    response.getWriter().write(JSON.toJSONString(Result.error("用户不存在")));
                    return;
                }

                // 检查车牌号是否已存在
                if (userCarDao.getByCarNum(parking.getCarNum()) != null) {
                    response.getWriter().write(JSON.toJSONString(Result.error("车牌号已存在")));
                    return;
                }

                userCarDao.insert(car);
//                parking.setEntryDate(new Date());
//                parking.setEntryTime(new Date());
                tempParkingDao.insert(parking);
                //获取刚添加的车辆ID
                car.setCarId(userCarDao.getByCarId(car.getCarNumber()));
                //更新车位状态：占用，车辆ID 车牌号，用户ID
                parkingSeatDao.updateSeatState(car.getSeatNum(), car.getCarId(), car.getCarNumber(), car.getUserId());
                response.getWriter().write(JSON.toJSONString(Result.success()));
                
            } else if ("/exit".equals(pathInfo)) {
                // 车辆出场
                String requestBody = request.getReader().readLine();
                System.out.println("requestBody: " + requestBody);
                TempParking parking = new TempParking();
                parking.setCarNum(requestBody);
                System.out.println("carNum: " + parking.getCarNum());
                parking.setCarNum(tempParkingDao.getByCarNum(parking.getCarNum()).get(0).getCarNum());
                System.out.println("carNum2: " + parking.getCarNum());
                if (parking.getCarNum() != null) {
                    // TODO: 计算费用, 计算公式：停车时间 * 每小时费用
                    // 获取入场时间:年月日
                    Timestamp entryDate = tempParkingDao.getEntryTimeByCarNum(parking.getCarNum());
                    //转换c
                    // 获取出场时间:年月日时分秒
                    Date outDate = new Date();
                    System.out.println("entryDate:-> " + entryDate);
                    System.out.println("outDate:-> " + outDate);
                    // 判断时间是否正确: 入场时间不能大于出场时间
                    if (outDate.getTime() - entryDate.getTime()<=0){
                        response.getWriter().write(JSON.toJSONString(Result.error("入场时间不能大于出场时间")));
                        return;
                    }
                    //如果停车时间小于1小时，则计1小时
                    if (outDate.getTime() - entryDate.getTime()<3600000){
                        tempParkingDao.update(5.0f,"不足1小时", parking.getCarNum());
                        Integer carId = userCarDao.getByCarId(parking.getCarNum());
                        System.out.println("carId----->" + carId);
                        parkingSeatDao.updateSeatStateByCarId(carId);
                        userCarDao.deleteById(carId);
                        response.getWriter().write(JSON.toJSONString(Result.success()));
                        return;
                    }
                    // 计算停车时间：可能不在同一天
                    long parkingTimeInMillis = outDate.getTime() - entryDate.getTime();
                    System.out.println("outDate: " + outDate.getTime());
                    System.out.println("entryDate: " + entryDate.getTime());
                    System.out.println("parkingTimeInMillis: " + parkingTimeInMillis);
                    long parkingTimeInMinutes = parkingTimeInMillis / (1000 * 60); // 转换为分钟

                    // 使用 String.format 来格式化小时和分钟，确保小时和分钟都有两位数显示
                    String hours = String.format("%02d", parkingTimeInMinutes / 60); // 计算小时，确保两位数
                    String minutes = String.format("%02d", parkingTimeInMinutes % 60); // 计算剩余分钟，确保两位数
                    String duration = hours + " 小时 " + minutes + " 分钟";

                    System.out.println("停车时长: " + duration);
                    // 设置每小时收费5元
                    float pricePerHour = 5.0f;
                      // 计算费用
                    BigDecimal fee = BigDecimal.valueOf(parkingTimeInMinutes / 60.0f).multiply(BigDecimal.valueOf(pricePerHour));
                    fee = fee.setScale(2, RoundingMode.HALF_UP); // 保留两位小数，四舍五入
                    
                    parking.setTempMoney(fee.floatValue());// 将 BigDecimal 转换为 float
                    System.out.println("fee: " + fee.floatValue());
                    tempParkingDao.update(parking.getTempMoney(),duration, parking.getCarNum());
                    Integer carId = userCarDao.getByCarId(parking.getCarNum());
                    System.out.println("carId:----->" + carId);
                    parkingSeatDao.updateSeatStateByCarId(carId);
                    userCarDao.deleteById(carId);
                    response.getWriter().write(JSON.toJSONString(Result.success()));
                } else {
                    response.getWriter().write(JSON.toJSONString(Result.error("找不到停车记录")));
                }
            }
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error(e.getMessage())));
        }
    }
} 